#include "trendwindow.h"
#include <QMainWindow>
#include <QWidget>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QVector>
#include <QDate>
#include <QPen>
#include <QBrush>
#include <QPointF>
#include <QGraphicsLineItem>
#include <QPen>
#include <QBrush>
#include <QColor>

TrendWindow::TrendWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle("BMI趋势分析");
    resize(600, 500);

    scene = new QGraphicsScene(this);
    graphicsView = new QGraphicsView(scene, this);
    setCentralWidget(graphicsView);
}

void TrendWindow::setBmiHistory(const QVector<double> &bmiValues, const QVector<QDate> &dates)
{
    scene->clear();
    
    // 计算坐标范围和比例
    double minBmi = *std::min_element(bmiValues.begin(), bmiValues.end());
    double maxBmi = *std::max_element(bmiValues.begin(), bmiValues.end());
    double range = maxBmi - minBmi;
    if (range < 5) range = 5; // 最小范围
    
    int width = graphicsView->width() - 50;
    int height = graphicsView->height() - 50;
    
    // 绘制坐标轴
    QPen axisPen(Qt::black, 2);
    scene->addLine(40, height, width, height, axisPen); // X轴
    scene->addLine(40, height, 40, 20, axisPen);       // Y轴
    
    // 绘制数据点
    QPen pointPen(Qt::blue, 3);
    QBrush pointBrush(Qt::blue);
    
    QVector<QPointF> points;
    for (int i = 0; i < bmiValues.size(); ++i) {
        int x = 40 + (i * width / (bmiValues.size() - 1));
        int y = height - ((bmiValues[i] - minBmi) * height / range);
        points.append(QPointF(x, y));
        scene->addEllipse(x-3, y-3, 6, 6, pointPen, pointBrush);
    }
    
    // 绘制连线
    QPen linePen(Qt::red, 2);
    for (int i = 1; i < points.size(); ++i) {
        scene->addLine(points[i-1].x(), points[i-1].y(), 
                      points[i].x(), points[i].y(), linePen);
    }
}